import { AppDispatch } from '@/store'
import { pubCommentsAPI } from '@/store/actions/article'
import { getError } from '@/utils/Error'
import { NavBar, TextArea, Toast } from 'antd-mobile'
import { TextAreaRef } from 'antd-mobile/es/components/text-area'
import { useEffect, useRef, useState } from 'react'
import { useDispatch } from 'react-redux'
import styles from './index.module.scss'
// 该组件的两个使用场景：1 文章评论  2 评论回复

type Props = {
  // 对评论回复时，需要传入该属性
  name?: string
  onClose?: () => void
  id: string
  total: number
}

const CommentInput = ({ name, onClose, id, total }: Props) => {
  const [value, setValue] = useState('')
  const textAreaRef = useRef<TextAreaRef>(null)

  useEffect(() => {
    textAreaRef.current?.focus()
  }, [])
  const onChange = (value: string) => {
    setValue(value)
  }
  const dispatch = useDispatch<AppDispatch>()
  const pubComment = async () => {
    try {
      await dispatch(
        pubCommentsAPI({
          payload: {
            target: id,
            content: value,
          },
          count: total + 1,
        })
      )
      onClose!()
      // onShowComment()
      Toast.show({
        icon: 'success',
        content: '发布评论成功',
      })
    } catch (error) {
      getError(error)
    }
  }

  return (
    <div className={styles.root}>
      <NavBar
        onBack={onClose}
        right={
          <span className="publish" onClick={pubComment}>
            发表
          </span>
        }>
        {name ? '回复评论' : '评论文章'}
      </NavBar>

      <div className="input-area">
        {name && <div className="at">@{name}:</div>}
        <TextArea
          ref={textAreaRef}
          placeholder="说点什么~"
          rows={6}
          value={value}
          onChange={onChange}
        />
      </div>
    </div>
  )
}

export default CommentInput
